package com.zhc.dejingapi.utils;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.util.CollectionUtils;

import java.io.*;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @Description:
 * @Author: zhangge
 * @Date: 2019-03-14
 */
@Slf4j
public class HttpClientUtil {
    private static Gson gson = new Gson();
    public static final String PUT = "PUT";

    /**
     * 发送post请求，参数用map接收
     *
     * @param url      地址
     * @param paramMap 参数
     * @return 返回值
     */

    public static String postFormData(String url, Map<String, String> paramMap) {
        OutputStreamWriter out = null;
        BufferedReader in = null;
        String result = "";
        String param = gson.toJson(paramMap);

        try {
            String boundary = UUID.randomUUID().toString().replace("-", "");

            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            conn.setReadTimeout(5000);
            conn.setConnectTimeout(5000);
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
//            out = new PrintWriter(conn.getOutputStream());
//            // 发送请求参数
//            out.print(param);
            out = new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8);
            out.write(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {

        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {

            }
        }

        return result;

    }


    /**
     * 发送post请求，参数用map接收
     *
     * @param url   地址
     * @param param 参数
     * @return 返回值
     */
    public static String postForm(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";

        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            log.error("act=postMap desc=发送POST请求出现异常！ paramMap={} ", param, e);
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                log.error("act=postMap desc=IOException paramMap={} error={}", param, ex);
            }
        }

        return result;

    }

    /**
     * post json类型
     * contentType为json
     *
     * @param url
     * @return
     */
    public static String postJson(String url, String json, Map<String, String> headers) {

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        post.setHeader("Content-Type", "application/json;charset=UTF-8");
        if (headers.size() > 0) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                String mapKey = entry.getKey();
                String mapValue = entry.getValue();
                post.setHeader(mapKey, mapValue);
            }
        }
        String response = null;
        try {
            StringEntity s = new StringEntity(json, "utf-8");
            post.setEntity(s);
            log.info("HttpUtilsConsumer.doPostJson请求入参post=" + JSON.toJSONString(post));
            HttpResponse res = httpClient.execute(post);

            if (HttpStatus.SC_OK <= res.getStatusLine().getStatusCode() && res.getStatusLine().getStatusCode() < HttpStatus.SC_MULTIPLE_CHOICES) {
                String result = EntityUtils.toString(res.getEntity());// 返回json格式：
                response = result;
                log.info(response);
            } else {
                log.info("postJson httpstatus error {} {}", res.getStatusLine().getStatusCode(), EntityUtils.toString(res.getEntity()));
                throw new Exception();
            }
        } catch (Exception e) {
            log.error("http接口调用失败" + ",url=" + url + ",param=" + json, e);
        }
        return response;
    }

    /**
     * post在basic auth下发送xml
     *
     * @param userName
     * @param password
     * @param soapXml
     * @return
     */
    public static String postXmlByBasicAuth(String url, String soapXml, String userName, String password) {
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        CredentialsProvider provider = new BasicCredentialsProvider();
        AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);
        // 此处填写用户名和密码
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userName, password);
        provider.setCredentials(scope, credentials);
        httpClientBuilder.setDefaultCredentialsProvider(provider);
        CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
        String result = "";
        HttpPost httpPost = null;
        HttpResponse httpResponse = null;
        HttpEntity entity = null;
        httpPost = new HttpPost(url);
        try {
            httpPost.setEntity(new StringEntity(soapXml));
        } catch (UnsupportedEncodingException e) {
            log.error("Method postXmlByBasicAuth Unsupported Encoding Exception");
            throw new RuntimeException();
        }
        httpPost.setHeader("Content-type", "text/xml");
        try {
            log.info("Send POST to Url: {}, Param: {}", url, soapXml);
            httpResponse = closeableHttpClient.execute(httpPost);
        } catch (IOException e) {
            e.printStackTrace();
        }
        entity = httpResponse.getEntity();
        if (entity != null) {
            try {
                result = EntityUtils.toString(entity);
                log.info("From url :{}, Result: {}", url, result);
            } catch (IOException e) {
                log.error("Method postXmlByBasicAuth HttpEntity transform String Exception");
                throw new RuntimeException();
            }
        }
        // 关闭连接
        try {
            closeableHttpClient.close();
        } catch (IOException e) {
            log.error("Method postXmlByBasicAuth  Close closeableHttpClient Exception");
            throw new RuntimeException();
        }
        return result;
    }

    public static String doGet(String url, Map<String, String> headParam) {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            //URIBuilder builder = new URIBuilder(url);
            //if (param != null) {
            //    for (String key : param.keySet()) {
            //        builder.setParameter(key, param.get(key));
            //    }
            //}
            if (headParam != null) {
                for (String key : headParam.keySet()) {
                    //builder.setParameter(key, param.get(key));

                }
            }
            //URI uri = builder.build();
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(url);
            log.info("DoGetUri========" + url);
            //if (!(apiKey==null   ||apiKey.isEmpty())) {
            //    httpGet.setHeader("Authorization", "Basic " + Base64.getUrlEncoder().encodeToString((apiKey + ":").getBytes()));
            //}
            if (headParam != null) {
                for (String key : headParam.keySet()) {
                    //builder.setParameter(key, param.get(key));
                    httpGet.setHeader(key,headParam.get(key));
                }
            }
            // 执行请求
            response = httpclient.execute(httpGet);
            log.info("ConvenientDoGet======={}", response);
            //System.out.println("返回状态码："+response.getStatusLine().getStatusCode());
            // 判断返回状态是否为200
            resultString = EntityUtils.toString(response.getEntity(), getDefaultCharSet());
            log.info("doGet()---result:" + resultString);
        } catch (Exception e) {
            log.error("doGet()方法调用失败");
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }
    /**
     * 功能描述 (发送get请求带参数)
     *
     * @param url    请求路径
     * @param param  请求参数集合，key-value格式：key为参数名，value为参数值
     * @param apiKey 请求的认证Apikey，若不存在直接传空就不会被赋值
     * @return
     * @author zhangce
     */
    public static String doGet(String url, Map<String, String> param, String apiKey) {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.setParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            log.info("DoGetUri========" + uri);
            if (!(apiKey==null   ||apiKey.isEmpty())) {
                httpGet.setHeader("Authorization", "Basic " + Base64.getUrlEncoder().encodeToString((apiKey + ":").getBytes()));
            }
            // 执行请求
            response = httpclient.execute(httpGet);
            log.info("ConvenientDoGet======={}", response);
            //System.out.println("返回状态码："+response.getStatusLine().getStatusCode());
            // 判断返回状态是否为200
            resultString = EntityUtils.toString(response.getEntity(), getDefaultCharSet());
            log.info("doGet()---result:" + resultString);
        } catch (Exception e) {
            log.error("doGet()方法调用失败");
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    /**
     * get发送请求
     *
     * @param url   请求路径
     * @param param 请求参数集合
     * @param
     * @return
     */
    public static String doGetParam(String url, Map<String, String> param, Map<String, String> headers) {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.setParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            if (headers.size() > 0) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    String mapKey = entry.getKey();
                    String mapValue = entry.getValue();
                    httpGet.setHeader(mapKey, mapValue);
                }
            }
            // 执行请求
            response = httpclient.execute(httpGet);
            resultString = EntityUtils.toString(response.getEntity(), getDefaultCharSet());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    /**
     * 设置编码格式utf-8,防止乱码
     *
     * @return utf-8
     */
    private static String getDefaultCharSet() {
        OutputStreamWriter writer = new OutputStreamWriter(new ByteArrayOutputStream());
        String enc = writer.getEncoding();
        return enc;
    }

    public static String putJson(String url, String json, Map<String, String> headers) {

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPut put = new HttpPut(url);
        put.setHeader("Content-Type", "application/json");
        if (headers.size() > 0) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                String mapKey = entry.getKey();
                String mapValue = entry.getValue();
                put.setHeader(mapKey, mapValue);
            }
        }
        String response = null;
        try {
            StringEntity s = new StringEntity(json, "utf-8");
            put.setEntity(s);
            log.info("HttpUtilsConsumer.doPostJson请求入参post=" + JSON.toJSONString(put));
            HttpResponse res = httpClient.execute(put);

            if (HttpStatus.SC_OK <= res.getStatusLine().getStatusCode() && res.getStatusLine().getStatusCode() < HttpStatus.SC_MULTIPLE_CHOICES) {
                String result = EntityUtils.toString(res.getEntity());// 返回json格式：
                response = result;
            } else {
                log.info("postJson httpstatus error {} {}", res.getStatusLine().getStatusCode(), EntityUtils.toString(res.getEntity()));
                throw new Exception();
            }
        } catch (Exception e) {
            log.error("http接口调用失败" + ",url=" + url + ",param=" + json, e);
        }
        return response;
    }

    /**
     * 支持put请求，在basic下参数为json形式
     *
     * @param url      请求路径
     * @param type     请求类型：默认post，put：HttpClientUtil.PUT
     * @param json     请求参数
     * @param username 用户名
     * @param password 密码（没有密码，设为空字符串：""）
     * @return 响应结果
     */
    public static String postAndPutJson(String url, String type, String json, String username, String password) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpEntityEnclosingRequestBase httpRequestBase = null;
        String result = "";
        if (PUT.equals(type)) {
            httpRequestBase = new HttpPut(url);
        } else {
            httpRequestBase = new HttpPost(url);
        }
        httpRequestBase.setHeader("Content-Type", "application/json;charset=UTF-8");
        if (password == null) {
            password = "";
        }
        httpRequestBase.setHeader("Authorization", "Basic " + Base64.getUrlEncoder().encodeToString((username + ":" + password).getBytes()));
        try {
            StringEntity s = new StringEntity(json, "utf-8");
            httpRequestBase.setEntity(s);
            log.info("HttpUtilsConsumer.postAndPutJson请求入参=" + JSON.toJSONString(httpRequestBase));
            HttpResponse res = httpClient.execute(httpRequestBase);
            result = EntityUtils.toString(res.getEntity());// 返回json格式：
        } catch (Exception e) {
            log.error("http接口调用失败" + ",url=" + url + ",param=" + json, e);
        }
        return result;
    }


    public static String doPost(String url,  String json, Map<String,String> headers) {
        // 设置请求配置，超时设置（单位是毫秒）
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(5000) // 连接超时时间
                .setSocketTimeout(60000)  // 数据读取超时时间
                .build();

        CloseableHttpClient httpClient = HttpClientBuilder
                .create()
                .setDefaultRequestConfig(requestConfig)
                .build();
        HttpEntityEnclosingRequestBase httpRequestBase = null;
        String result = "";




        httpRequestBase = new HttpPost(url);

        httpRequestBase.setHeader("Content-Type", "application/json;charset=UTF-8");
        if(headers==null||headers.isEmpty()||headers.size()==0){

        }
        else{
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                String mapKey = entry.getKey();
                String mapValue = entry.getValue();
                httpRequestBase.setHeader(mapKey, mapValue);
            }
        }

        //String apiKey
        //httpRequestBase.setHeader("Authorization", "Basic " + Base64.getUrlEncoder().encodeToString((apiKey + ":").getBytes()));
        try {
            StringEntity s = new StringEntity(json, "utf-8");
            httpRequestBase.setEntity(s);
            log.info("HttpUtilsConsumer.postAndPutJson请求入参=" + JSON.toJSONString(httpRequestBase));
            HttpResponse res = httpClient.execute(httpRequestBase);
            result = EntityUtils.toString(res.getEntity());// 返回json格式：
        } catch (Exception e) {
            log.error("http接口调用失败" + ",url=" + url + ",param=" + json, e);
        }
        return result;
    }

    /**
     * 支持put请求，在basic下参数为json形式
     *
     * @param url      请求路径
     * @param type     请求类型：默认post，put：HttpClientUtil.PUT
     * @param json     请求参数
     * @param username 用户名
     * @param password 密码（没有密码，设为空字符串：""）
     * @return 响应结果
     */
    public static String postAndPutJson(String url, String type, String json, String username, String password, Map<String, String> headers) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpEntityEnclosingRequestBase httpRequestBase = null;
        String result = "";
        if (PUT.equals(type)) {
            httpRequestBase = new HttpPut(url);
        } else {
            httpRequestBase = new HttpPost(url);
        }
        httpRequestBase.setHeader("Content-Type", "application/json;charset=UTF-8");
        if (password == null) {
            password = "";
        }
        httpRequestBase.setHeader("Authorization", "Basic " + Base64.getUrlEncoder().encodeToString((username + ":" + password).getBytes()));
        if (headers.size() > 0) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                String mapKey = entry.getKey();
                String mapValue = entry.getValue();
                httpRequestBase.setHeader(mapKey, mapValue);
            }
        }
        try {
            StringEntity stringEntity = new StringEntity(json, "utf-8");
            httpRequestBase.setEntity(stringEntity);
            log.info("HttpUtilsConsumer.postAndPutJson请求入参=" + JSON.toJSONString(httpRequestBase));
            HttpResponse res = httpClient.execute(httpRequestBase);
            result = EntityUtils.toString(res.getEntity());// 返回json格式：
        } catch (Exception e) {
            log.error("http接口调用失败" + ",url=" + url + ",param=" + json, e);
        }
        return result;
    }


    /**
     * 支持put请求，在basic下参数为json形式
     *
     * @param url  请求路径
     * @param type 请求类型：默认POST，PUT：HttpClientUtil.PUT 由于equils比较的一定记得区分大小写
     * @param json 请求参数
     * @return 响应结果
     */
    public static String postAndPutJson(String url, String type, String json, String apiKey) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpEntityEnclosingRequestBase httpRequestBase = null;
        String result = "";
        if (PUT.equals(type)) {
            httpRequestBase = new HttpPut(url);
        } else {
            httpRequestBase = new HttpPost(url);
        }
        httpRequestBase.setHeader("Content-Type", "application/json;charset=UTF-8");
        httpRequestBase.setHeader("Authorization", "Basic " + Base64.getUrlEncoder().encodeToString((apiKey + ":").getBytes()));
        try {
            StringEntity s = new StringEntity(json, "utf-8");
            httpRequestBase.setEntity(s);
            log.info("HttpUtilsConsumer.postAndPutJson请求入参=" + JSON.toJSONString(httpRequestBase));
            HttpResponse res = httpClient.execute(httpRequestBase);
            result = EntityUtils.toString(res.getEntity());// 返回json格式：
        } catch (Exception e) {
            log.error("http接口调用失败" + ",url=" + url + ",param=" + json, e);
        }
        return result;
    }
    /*
     * post在basic auth下发送json
     * @param json
     * @param apiKey
     * @return
     */
    public static String postJsonByBasicAuth(String url, String json, String apiKey) {
        CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build();
        String result = "";
        HttpPost httpPost = null;
        HttpResponse httpResponse = null;
        HttpEntity entity = null;
        httpPost = new HttpPost(url);
        try {
            if(!(json==null||json.isEmpty()||json.equals(""))){
                httpPost.setEntity(new StringEntity(json, "UTF-8"));
            }
            httpPost.setHeader("Authorization", "Basic " + Base64.getUrlEncoder().encodeToString((apiKey + ":").getBytes()));
        } catch (Exception e) {
            log.error("Method postXmlByBasicAuth Unsupported Encoding e: {} ,message: {}", e, e.getMessage());
            throw new RuntimeException();
        }
        httpPost.setHeader("Content-Type", "application/json; charset=utf-8");
        try {
            log.info("Send POST to Url: {}, Param: {}", url, json);
            httpResponse = closeableHttpClient.execute(httpPost);
        } catch (IOException e) {
            e.printStackTrace();
        }
        entity = httpResponse.getEntity();
        if (entity != null) {
            try {
                result = EntityUtils.toString(entity);
                log.info("From url :{}, Param: {}, Result: {}", url, json, result);
            } catch (IOException e) {
                log.error("Method postXmlByBasicAuth HttpEntity transform String Exception");
                throw new RuntimeException();
            }
        }
        // 关闭连接
        try {
            closeableHttpClient.close();
        } catch (IOException e) {
            log.error("Method postXmlByBasicAuth  Close closeableHttpClient Exception");
            throw new RuntimeException();
        }
        return result;
    }

    /**
     * post x-www-form-urlencoded类型
     *
     * @param url 访问地址
     * @param map 传入参数
     * @return 响应结果
     */
    public static String postFormUrlencoded(String url, Map<String, String> map) {
        String result = "";
        HttpResponse res = null;
        List<NameValuePair> pairs = new ArrayList<>();
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);
        try {
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
            if (!CollectionUtils.isEmpty(map)) {
                map.forEach((key, value) -> pairs.add(new BasicNameValuePair(key, value)));
                httpPost.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8"));
            }
            log.info("HttpClientUtil.postFormUrlencoded=", pairs);
            res = httpClient.execute(httpPost);
            if (HttpStatus.SC_OK <= res.getStatusLine().getStatusCode() && res.getStatusLine().getStatusCode() < HttpStatus.SC_MULTIPLE_CHOICES) {
                result = EntityUtils.toString(res.getEntity());// 返回json格式：
            } else {
                log.info("postFormUrlencoded httpstatus error {} {}", res.getStatusLine().getStatusCode(), EntityUtils.toString(res.getEntity()));
                throw new Exception();
            }
        } catch (Exception e) {
            log.error("http接口调用失败" + ",url=" + url + ",param=" + JSONObject.toJSONString(pairs), e);
        }
        return result;
    }


    public static String doDel(String url, Map<String, String> headParam,String strJSONBody) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Delete请求
            //HttpDelete httpDelete = new HttpDelete(url);
            HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(url);
            // 创建参数列表
            URIBuilder builder = new URIBuilder(url);
            //if (param != null) {
            //    for (String key : param.keySet()) {
            //        builder.addParameter(key, param.get(key));
            //    }
            //}
            URI uri = builder.build();
            httpDelete.setURI(uri);

            //if (!(apiKey.isEmpty())) {
            //    httpDelete.setHeader("Authorization", "Basic " + Base64.getUrlEncoder().encodeToString((apiKey + ":").getBytes()));
            //}
            if (headParam != null) {
                for (String key : headParam.keySet()) {
                    httpDelete.setHeader(key,headParam.get(key));
                }
            }

            /*
            其他代码
            其他 例如设置头信息，设置请求配置参数等等 无需修改，对象替换为  第一句定义的即可
            jsonBody 为你的 JSON 参数
            */
            StringEntity entity = new StringEntity(strJSONBody, ContentType.APPLICATION_JSON);
            httpDelete.setEntity(entity);

            //原文链接：https://blog.csdn.net/weixin_44131922/article/details/123292726

            response = httpClient.execute(httpDelete);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), getDefaultCharSet());
                log.info("doDelete()---result:" + resultString);

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return resultString;
    }
    public static String doDelete(String url, Map<String, String> param, String apiKey) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Delete请求
            HttpDelete httpDelete = new HttpDelete(url);
            // 创建参数列表
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();
            httpDelete.setURI(uri);

            if (!(apiKey.isEmpty())) {
                httpDelete.setHeader("Authorization", "Basic " + Base64.getUrlEncoder().encodeToString((apiKey + ":").getBytes()));
            }

            response = httpClient.execute(httpDelete);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), getDefaultCharSet());
                log.info("doDelete()---result:" + resultString);

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return resultString;
    }

    public static String doDelete(String url, Map<String, String> param,String strJSON, String apiKey) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Delete请求
            //HttpDelete httpDelete = new HttpDelete(url);
            HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(url);
            // 创建参数列表
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();
            httpDelete.setURI(uri);

            if (!(apiKey.isEmpty())) {
                httpDelete.setHeader("Authorization", "Basic " + Base64.getUrlEncoder().encodeToString((apiKey + ":").getBytes()));
            }

            /*
            其他代码
            其他 例如设置头信息，设置请求配置参数等等 无需修改，对象替换为  第一句定义的即可
            jsonBody 为你的 JSON 参数
            */
            StringEntity entity = new StringEntity(strJSON, ContentType.APPLICATION_JSON);
            httpDelete.setEntity(entity);

            //原文链接：https://blog.csdn.net/weixin_44131922/article/details/123292726

            response = httpClient.execute(httpDelete);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), getDefaultCharSet());
                log.info("doDelete()---result:" + resultString);

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return resultString;
    }



    /**
     * 功能描述 (发送put请求带参数)
     *
     * @param url
     * @param param
     * @param apiKey 请求的认证Apikey，若不存在直接传空就不会被赋值
     * @return
     * @author zhangce
     * @date
     */
    public static String doPut(String url, Map<String, String> param, String apiKey) {

        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();

            // 创建http PUT请求
            HttpPut httpPut = new HttpPut(uri);
            //添加apikey
            if (!(apiKey.isEmpty())) {

                httpPut.setHeader("Authorization", "Basic " + Base64.getUrlEncoder().encodeToString((apiKey + ":").getBytes()));
            }
            // 执行请求
            response = httpclient.execute(httpPut);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), getDefaultCharSet());
                log.info("doPut()---result:" + resultString);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }


    /**
     * 功能描述 (发送get请求带参数)
     *
     * @param url    请求路径
     * @param param  请求参数集合，key-value格式：key为参数名，value为参数值
     * @param apiKey 请求的认证Apikey，若不存在直接传空就不会被赋值
     * @return
     * @author zhangce
     */
    public static String doGet(String url, Map<String, String> param, String apiKey, String username, String password) {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.setParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            log.info("DoGetUri========" + uri);
            if (!(apiKey.isEmpty())) {
                httpGet.setHeader("Authorization", "Basic " + Base64.getUrlEncoder().encodeToString((apiKey + ":").getBytes()));
            }
            if (!(username.isEmpty())) {
                httpGet.setHeader("Authorization", "Basic " + Base64.getUrlEncoder().encodeToString((username + ":" + password).getBytes()));
            }
            // 执行请求
            response = httpclient.execute(httpGet);
            log.info("ConvenientDoGet======={}", response);
            //System.out.println("返回状态码："+response.getStatusLine().getStatusCode());
            // 判断返回状态是否为200
            resultString = EntityUtils.toString(response.getEntity(), getDefaultCharSet());
            log.info("doGet()---result:" + resultString);
        } catch (Exception e) {
            log.error("doGet()方法调用失败");
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static void main(String[] args) throws Exception {

        String s="[{\"department_code\":\"ididid111123\",\"sequence\":0,\"name\":\"namenamename1221\"},{\"department_code\":\"ididid211123\",\"name\":\"namenamename21_testhema\",\"parent_code\":\"ididid31112\"},{\"department_code\":\"ididid311123\",\"department_id\":387,\"name\":\"namenamename222test_hema\",\"parent_code\":\"huangtiandi\",\"type\":2}]";

        HttpClientUtil.postAndPutJson("https://app.mokahr.com/api/outer/admin-api-task/node-run/notify/xCngPpEQHvo/yWYyXH_em8M/fbVOGY-RmUU","POST",s,"gVJQ1mnlnA92syJhCaeZO4IMMH9bGS8d");


    }

}